package cn.tedu.ivosback.base.file;

import cn.tedu.ivosback.base.response.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file")
public class UploadController {
    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

    /* 定义处理图片上传的方法
     * MultipartFile是Spring框架中用于处理文件上传的接口
     * 方法的形参名"file"必须与前端upload上传组件的name值一致!
     * */
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;
        String dirPath = "D:/uploadFiles";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = simpleDateFormat.format(new Date());
        File fileDir = new File(dirPath + datePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        file.transferTo(new File(dirPath + datePath + fileName));
        return JsonResult.ok(datePath + fileName);
    }

    @PostMapping("remove")
    public JsonResult remove(String imgUrl) {
        log.debug("删除图片:imgUrl={}", imgUrl);
        File file = new File("D:/uploadFiles" + imgUrl);
        if (file.exists()) {
            file.delete();
        }
        return JsonResult.ok();
    }
}
